#!/usr/bin/env python
import FetchBook
import FetchPic
import os
import urllib
import sys
import xml.dom.minidom
import model

def download(books):
    for book in books:
        if(not os.path.exists("/Users/fatian/code/huiben/"+book[0].decode('utf8'))):
            FetchPic.downloadbook("/Users/fatian/code/huiben/"+book[0].decode('utf8'))
        FetchPic.uploadbook(book[0].decode('utf8'),book[1])
        print book[0].decode('utf8')

    print 'finish'

    return None

def fetchPopular():
    books = FetchBook.doParse("http://app2.xingbook.com/r/ph.do?t=112")
    print books;

    download(books)
    return None

def fetchPage(start):
    params=urllib.urlencode({'n':20,'t':112,'d':0,'tag':0,'s':start,'a':0,'o':0})
    print params
    f=urllib.urlopen("http://app2.xingbook.com/r/ss.do",params)
    data = f.read().encode("UTF-8")
    dom = xml.dom.minidom.parseString(data)
    books= FetchBook.parseDom(dom);
    print len(books),books
    download(books)
    return len(books)

def fetchAll():
    start = 0
    while(True):
        len = fetchPage(start)
        if (len < 20):
            break
        start += 20


#fetchPopular()
fetchAll()
#fetchPage(529)
